package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.dto.CheckInApplyDto;
import com.zzyl.nursing.domain.dto.CheckInConfigDto;
import com.zzyl.nursing.domain.dto.CheckInContractDto;
import com.zzyl.nursing.domain.dto.CheckInElderDto;
import com.zzyl.nursing.domain.pojo.*;
import com.zzyl.nursing.domain.vo.CheckInConfigVo;
import com.zzyl.nursing.domain.vo.CheckInDetailVo;
import com.zzyl.nursing.domain.vo.CheckInElderVo;
import com.zzyl.nursing.domain.vo.ElderFamilyVo;
import com.zzyl.nursing.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-05-19
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住

     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     *  添加申请入住信息
     * @param dto
     */
    @Transactional
    @Override
    public void checkInApply(CheckInApplyDto dto) {
        // 校验
        // 1，判断老人是否存在
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();

        Elder elderDb = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getName, checkInElderDto.getName())
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus, 1));

        if (ObjectUtils.isNotNull(elderDb)) {
            throw new ServiceException("老人已存在");
        }

        // 2,新增
        // 2.1更新·床
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        Bed bed = bedMapper.selectBedById(checkInConfigDto.getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);

        // 2.2 老人--》更新或新增
        Elder insertOrUpdateElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getName, checkInElderDto.getName())
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus, 1));


        Elder elder = new Elder();
        BeanUtil.copyProperties(checkInElderDto,elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        if(ObjectUtils.isNotNull(insertOrUpdateElder)){
            elder.setId(insertOrUpdateElder.getId());
            elderMapper.updateElder(elder);
        }else {
            elderMapper.insert(elder);
        }

        // 合同新增
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);

        // 入住配置
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkInMapper.insert(checkIn);

        // 新增入住配置信息

        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 根据id查询详细信息
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getOneInfo(Long id) {
        //1 从表中查询老人基本信息
        CheckIn checkIn = this.getById(id);
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getId, checkIn.getElderId()));
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        // 根据生日计算老人年龄
        String birthday = checkInElderVo.getBirthday();
        LocalDate birth = LocalDate.parse(birthday);
        Period period = Period.between(birth,LocalDate.now());
        int age = period.getYears();
        checkInElderVo.setAge(age);

        // 查询合同信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elder.getId()));

        // 从表中查到配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        if(ObjectUtils.isNotNull(checkInConfigVo)){
            checkInConfigVo.setBedNumber(checkIn.getBedNumber());
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());
        }

        // 查询老人关联的家属信息
        ElderFamilyVo elderFamilyVo = BeanUtil.toBean(contract, ElderFamilyVo.class);
        elderFamilyVo.setName(contract.getThirdPartyName());
        elderFamilyVo.setPhone(contract.getThirdPartyPhone());
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
        elderFamilyVoList.add(elderFamilyVo);

        // 将数据整合到CheckInDetailVo返回
        return new CheckInDetailVo(checkInElderVo,elderFamilyVoList,checkInConfigVo,contract);
    }
}
